<?php

class Photo_Controller_Browse_Upload extends Nuo_Controller
{
	function execute($request)
	{
		if (!Nuo::allow('photo.addNew'))
		{
			return 'could not upload photo';
			return;
		}

		$form = Nuo::getObject('photo/upload', 'form');

		$mainResourceId = $request -> getParam('resource-item');

		$mainResource = NULL;

		if ($mainResourceId)
		{
			$mainResource = Nuo::getItem($mainResourceId);
		}

		if (!$mainResource)
		{
			$mainResource = Nuo::getUser();
		}

		$table = Nuo::getTable('photo');

		$poster = Nuo::getUser();

		if ($request -> isPost() && $form -> isValid($_POST))
		{

			$uploads = Nuo_Filesystem::instance() -> getUploads('photo');

			$data = $form -> getData();

			$files = array();

			if ($uploads)
			{
				$files = Nuo::getApi('core/image') -> processAll($uploads, 'photo');
			}

			$counter = 0;

			/**
			 * first select
			 */
			$mainPhoto = null;
			$photos = array();

			foreach ($files as $file)
			{
				$item = $table -> fetchNew();
				$item -> setPhotoFile($file);
				$item -> created_at = time();
				$item -> setResource($mainResource) -> setPoster($poster);
				$item -> save();
				$photos[] = $item;
				if (NULL == $mainPhoto)
				{
					$mainPhoto = $item;
				}
				++$counter;
			}

			/**
			 * get viewer
			 */
			$viewer = $poster = Nuo::getUser();

			/**
			 * add activity feed to action
			 */

			if (is_object($mainPhoto))
			{
				$privacy = array('value' => $data['privacy']);
				$feed = Nuo::getApi('activity') -> addFeed($poster, $mainResource, $mainPhoto, 'photo:addNew', $privacy);
			}

			if ($feed)
			{
				$attatchment = Nuo::getApi('core/attachment') -> addAttachments($feed, $photos);
			}

			if ($mainPhoto)
			{
				$uri = $mainResource -> getUrl('photo');
				Nuo::redirect($uri);
			}

		}
		return $form -> __toString();
	}

}
